package com.ca.singlesignon.controller;

import com.ca.singlesignon.entity.UserEntity;
import com.ca.singlesignon.service.UserService;
import com.ca.singlesignon.utils.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 主要是用作springSession
 */

@Controller
@RequestMapping("/user/springSession")
public class UserSpringSessionController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录接口
     *
     * @param username
     * @param password
     * @param session
     * @return
     */
    @PostMapping(value = "login")
    @ResponseBody
    public ServerResponse<UserEntity> login(String username, String password, HttpSession session) {

        ServerResponse<UserEntity> response = userService.login(username, password);
        if (response.isSuccess()) {
            session.setAttribute("currentUser", response.getData());
        }
        return response;
    }
    //退出登录
       @RequestMapping(value = "logout", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> logout(HttpSession session){
           session.removeAttribute("currentUser");
           return ServerResponse.createBySuccessMessage("注销成功");
    }


    @RequestMapping(value = "get_user_info", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<UserEntity> getUserInfo(HttpSession session) {
        UserEntity user =(UserEntity)session.getAttribute("currentUser");
        if(user!=null){
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户未登录,无法获取当前信息");
    }

}